<template>
  <div>
    <new-header v-bind:header="header"></new-header>
    <div class="form">
      <div class="row-2">
        <div class="label">
          姓名
        </div>
        <div class="input">
          <input type="text" placeholder="请输入您的真实姓名" v-model.trim="staff.name">
        </div>
        <div class="clearfix"></div>
      </div>
      <div class="row-4">
          <input  name="course" class="u-option-input" type="radio" id="one" value="10" v-model="picked" />
          <label for="one"><span ></span>成人课程</label>

          <input  name="course" class="u-option-input" type="radio" id="two" value="31" v-model="picked"/>
          <label for="two"><span></span>青少儿课程</label>
   </div>

      <div class="row-2">
        <div class="label">
          手机
        </div>
        <div class="input">
          <input type="text" placeholder="请输入11位手机号码" v-model.trim="staff.mobile">
        </div>
        <div class="clearfix"></div>
      </div>
      <!-- <div class="row-2">
        <div class="label">
          邮箱
        </div>
        <div class="input">
          <input type="text" placeholder="请输入邮箱地址" v-model.trim="staff.email">
        </div>
        <div class="clearfix"></div>
      </div> -->
      <div class="row-2">
        <div class="label">
          预约
        </div>
        <div class="input select" v-on:click="showDateList()">
          <div class="plachoder" v-show="staff.date.length===0">
            请选择预约日期
          </div>
          <div class="selected" v-show="staff.date.length!==0">
            {{staff.date}}
          </div>
          <div class="arrow-right">
            <img src="../assets/img/right@3x.png"/>
          </div>
        </div>
        <div class="clearfix"></div>
      </div>
      <div class="button submit" id="redsubmit">
        <div v-show="!isConfirm" v-on:click="confirm()">
          确认
        </div>
        <div class="loading" v-show="isConfirm">
          <img src="../assets/img/loading@3x.png"/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import newHeader from "../components/new-header";
import $ from "../assets/js/jquery.min.js";
import weuiCss from "../assets/css/weui.min.css";
import weui from "../assets/js/weui.min.js";
import { mapState, mapActions } from "vuex";
import { USER_SIGNIN } from "../store/user";

export default {
  name: "form",
  data() {
    return {
      picked: "10",
      header: {
        cnTitle: "请输入，获得免费在线课程",
        cnStyle: {
          fontSize: "20px",
          marginTop: "15px"
        }
      },
      staff: {
        name: "",
        gender: 1,
        mobile: "",
        email: "",
        date: "",
        ageValue: "",
        age: ""
      },
      isConfirm: false,
      token:"",
      mediaSn:""

    };
  },
  	created: function() {
    // var _that = this;
    // var token = getUrlParam("token");
    // var mediaSn = getUrlParam("mediaSn");
    // console.log(token)
    // console.log(mediaSn)
    //   var urlroot = urlchange;
    //   var url = urlroot+'/OMLeadKeyinRequest';
		// 	$.ajax({
		// 		type: 'GET',
		// 		url: url,
		// 		dataType: "jsonp",
		// 		data: {
		// 			"key": "omleadkeyin",
		// 			//"parameters": "token=" + _that.user.token,
		// 			"ContentType": "application/x-www-form-urlencoded",
		// 			"fun": "callbackFun",
		// 			//"token": "z6fYujYV/QAKehzfyAI8ZxAVWto="
    //        "token": token,
    //       //"token":"undefined",
    //       "ClientIp":"",
    //       "mediaSn":mediaSn
		// 		},
		// 		jsonpCallback: "callbackFun",
		// 		success: function(result) {
		// 			//var jsonResult = JSON.parse(result)[0];
    //        var jsonResult = result.ResultInfo;
		// 			if(result.IsSuccess==false) {
    //         alert("token无效,请重新登录");
    //          _that.$router.push('/login')
    //       }
    //      else {
    //         if(result.ResultInfo.msgcode >= 0) {} else {
    //           alert("token无效,请重新登录");
    //            _that.$router.push('/login');
    //         }

		// 			}
		// 		},
		// 		error: function(error) {
		// 			alert("系统异常");
		// 		}
    // 	});


		},
  mounted(){
      var _that = this;
      _that.token = this.$route.query.token;
      _that.mediaSn = this.$route.query.mediaSn;
      var urlroot = urlchange;
      var url = urlroot+'/OMLeadKeyinRequest';
			$.ajax({
				type: 'GET',
				url: url,
				dataType: "jsonp",
				data: {
					"key": "omleadkeyin",
					"ContentType": "application/x-www-form-urlencoded",
					"fun": "callbackFun",
           "token": _that.token,
          "ClientIp":"",
          "mediaSn":_that.mediaSn
				},
				jsonpCallback: "callbackFun",
				success: function(result) {
          console.log(result)
					//var jsonResult = JSON.parse(result)[0];
           var jsonResult = result.ResultInfo;
					if(result.IsSuccess==false) {
            alert("token无效,请重新登录");
              _that.$router.push('/login')
          }
         else {
            if(result.ResultInfo.msgcode >= 0) {

            } else {
              alert("token无效,请重新登录");
                _that.$router.push('/login');
            }

					}
				},
				error: function(error) {
					alert("系统异常");
				}
			});

  },
  methods: {
    ...mapActions([USER_SIGNIN]),
    //  geturlparam: function() {
    //  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    //   var r = window.location.search.substr(1).match(reg);
    //   if (r != null) return unescape(r[2]);
    //    return null;
    // },
    confirm: function() {
      var _that = this;
      var errorMsg = "";
      if (_that.staff.name.length === 0) {
        errorMsg += "请输入您的姓名\n";
      } else if (!/^[a-zA-Z\u4e00-\u9fa5]+$/.test(_that.staff.name)) {
        errorMsg += "姓名请确认格式,仅可输入全中文或全英文\n";
      }
      if (
        !/^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(
          _that.staff.mobile
        )
      ) {
        errorMsg += "请填写您的移动电话号码,需要填写正确11码\n";
      }

      if (!_that.staff.date) {
        errorMsg += "请选择预约日期\n";
      }
      if (errorMsg.length !== 0) {
        alert(errorMsg);
      } else {
        _that.isConfirm = true;
        var urlroot = urlchange;
        var url = urlroot + "/OMSaveLeadRequest";
        var closeAjax = $.ajax({
          type: "GET",
          url: url,
          dataType: "jsonp",
          data: {
            key: "omleadkeyin",
            ContentType: "application/x-www-form-urlencoded",
            fun: "callbackFun",
            token: _that.token,
            name: _that.staff.name,
            cphone: _that.staff.mobile,
            email: _that.staff.mobile+"@default.com",
            sex: "1",
            age_area: _that.picked,
            fromwhere: "aa",
            demodate: _that.staff.date,
            node: "",
            ClientIp: "",
            mediaSn:  _that.mediaSn
          },
          jsonpCallback: "callbackFun",
          success: function(result) {
            _that.isConfirm = false;
            if (result.IsSuccess == false) {
              if (result.ErrMsg == "OMRepeatData") {
                alert("该手机6个月之内已留过名单");
              } else if (result.ErrMsg == "NotValid") {
                alert("请邮箱是否输入正确");
              } else {
                alert(result.ErrMsg);
              }
              _that.isConfirm = false;
            } else {
              var jsonResult = result.ResultInfo;
              if (jsonResult.msgcode >= 0) {
                if (jsonResult.msgcode == 1) {
                  alert("客户已在其他渠道留过名单");
                }
                _that.user.lead_sn = jsonResult.lead_sn;
                _that.user.customer_name = _that.staff.name;
                _that.user.todaycount = jsonResult.todayconut;
                _that.USER_SIGNIN(_that.user);
                _that.$router.push("/thank");
              } else {
                alert("token失效.请重新登录");
                _that.$router.push("/login");
              }
            }
          },
          error: function(error) {
            alert("系统异常");
            _that.isConfirm = false;
          }
        });
      }
    },
    showDateList: function() {
      var _that = this;
      var dateNow = new Date();
      weui.picker(_that.dateList, {
        defaultValue: [
          dateNow.getFullYear(),
          dateNow.getMonth() + 1,
          dateNow.getDate()
        ],
        onChange: function(result) {},
        onConfirm: function(result) {
          _that.staff.date =
            result[0] + "/" + result[1] + "/" + result[2] + " " + result[3];
        },
        id: "datePicker"
      });
    },
    addDay: function(date, n) {
      var time = date.getTime();
      var newTime = time + n * 24 * 60 * 60 * 1000;
      return new Date(newTime);
    },
    getDateList: function(start, end) {
      var result = [];
      var years = [];
      var year = {};
      var months = [];
      var month = {};
      var days = [];
      var day = {};
      var time = [];
      var staYear = start.getFullYear();
      var staMon = start.getMonth() + 1;
      var endYear = end.getFullYear();
      var endMon = end.getMonth() + 1;
      var staDay = 1;
      var endDay = 1;
      while (staYear <= endYear) {
        if (staYear === start.getFullYear()) {
          staMon = start.getMonth() + 1;
          if (start.getFullYear() === end.getFullYear()) {
            endMon = end.getMonth() + 1;
          } else {
            endMon = 12;
          }
        } else if (staYear === end.getFullYear()) {
          staMon = 1;
          endMon = end.getMonth() + 1;
        } else {
          staMon = 1;
          endMon = end.getMonth() + 12;
        }

        year = { label: staYear, value: staYear, children: [] };

        while (staMon <= endMon) {
          month = { label: staMon, value: staMon, children: [] };
          if (
            staYear === start.getFullYear() &&
            staMon === start.getMonth() + 1
          ) {
            staDay = start.getDate();
            endDay = new Date(staYear, staMon, 0).getDate();
          } else if (
            staYear === end.getFullYear() &&
            staMon === end.getMonth() + 1
          ) {
            staDay = 1;
            endDay = end.getDate();
          } else {
            staDay = 1;
            endDay = new Date(staYear, staMon, 0).getDate();
          }
          while (staDay <= endDay) {
            time = [
              { label: "早上", value: "早上" },
              { label: "下午", value: "下午" },
              { label: "晚上", value: "晚上" }
            ];

            if (
              staYear === start.getFullYear() &&
              staMon === start.getMonth() + 1 &&
              staDay === start.getDate()
            ) {
              if (start.getHours() <= 12) {
                time = [
                  { label: "下午", value: "下午" },
                  { label: "晚上", value: "晚上" }
                ];
              } else {
                time = [{ label: "晚上", value: "晚上" }];
              }
            }
            day = { label: staDay, value: staDay, children: time };
            staDay++;
            month.children.push(day);
          }
          staMon++;
          year.children.push(month);
        }

        staYear++;
        years.push(year);
      }

      return years;
    }
  },
  computed: {
    dateList: function() {
      var dateNow = new Date();
      var endDate = this.addDay(dateNow, 30);

      return this.getDateList(dateNow, endDate);
    },
    brandId: function() {
      return this.age > 13 ? 4 : 2;
    },
    ...mapState(["user"])
  },
  components: { newHeader }
};
</script>
<style>
.qrcode {
  display: inline-block;
  position: absolute;
  right: 0;
  top: 0px;
  width: 15%;
}
.qrcode img {
  width: 100%;
}
.u-option-input {
    display: none;
}

/* .u-option-input+label{
      margin-right: 20px;

} */
/* .u-option-input+label::before {
    content: '';
    display: inline-block;
    background-position: center;
    background-repeat: no-repeat;
    background-size: 100%;
    background-image: url("../assets/img/us@1x.png");


    vertical-align: middle;

    width: 20px;
    height:20px;

    text-align:right;
}
.u-option-input:checked+label::before {
    background-image: url("../assets/img/s@1x.png");
} */
/* .u-option-input+label{
  display: inline-block;
   margin-right:5%;
}
.u-option-input+label span{
    display: inline-block;
    background-position: center;
    background-repeat: no-repeat;
    background-size: 100%;
    background-image: url("../assets/img/us@1x.png");
    vertical-align: middle;
    width: 22px;
    height:22px;
    margin-right:5px;


}
.u-option-input:checked+label span {
    background-image: url("../assets/img/s@1x.png");
    } */

</style>
